<!DOCTYPE html>



  


<html class="theme-next pisces use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">



  <meta name="google-site-verification" content="k-_TfM33aVJFwi1JD8Y3HUhdvKJQH6zfXGr9IifVEas">














  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=5.1.3" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/favicon-32x32.png?v=5.1.3">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32.png?v=5.1.3">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16.png?v=5.1.3">


  <link rel="mask-icon" href="/images/favicon-32x32.png?v=5.1.3" color="#222">





  <meta name="keywords" content="Hexo, NexT">










<meta name="description" content="Java 8 问世三年了，9马上也要问世了，所以，嗯，我要开始学8了……  官方文档：http://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html 为什么用Lambda表达式只是代码简洁了这个好处的话，并不能打动很多观众，java 8">
<meta property="og:type" content="article">
<meta property="og:title" content="深入理解Java-8-Lambda表达式（Oracle官方文档版）">
<meta property="og:url" content="https://angular2.top/posts/5913/index.html">
<meta property="og:site_name" content="大括号">
<meta property="og:description" content="Java 8 问世三年了，9马上也要问世了，所以，嗯，我要开始学8了……  官方文档：http://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html 为什么用Lambda表达式只是代码简洁了这个好处的话，并不能打动很多观众，java 8也不会这么令人期待，其实java 8引入lambda迫切需求是因为lambda">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="http://upload-images.jianshu.io/upload_images/2833665-be157a8464886ba7.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="http://upload-images.jianshu.io/upload_images/2833665-5a47139c88b47626.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:updated_time" content="2017-11-21T03:03:59.226Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="深入理解Java-8-Lambda表达式（Oracle官方文档版）">
<meta name="twitter:description" content="Java 8 问世三年了，9马上也要问世了，所以，嗯，我要开始学8了……  官方文档：http://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html 为什么用Lambda表达式只是代码简洁了这个好处的话，并不能打动很多观众，java 8也不会这么令人期待，其实java 8引入lambda迫切需求是因为lambda">
<meta name="twitter:image" content="http://upload-images.jianshu.io/upload_images/2833665-be157a8464886ba7.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Pisces',
    version: '5.1.3',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://angular2.top/posts/5913/">





  <title>深入理解Java-8-Lambda表达式（Oracle官方文档版） | 大括号</title>
  





  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?8953b3d3866338b66f755c911e6136f4";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>




</head>

<body itemscope="" itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope="" itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">大括号</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">是时候表演真正的技术了</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br>
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            归档
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope="" itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://angular2.top/posts/5913/">

    <span hidden itemprop="author" itemscope="" itemtype="http://schema.org/Person">
      <meta itemprop="name" content="无可替代">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/touxiang.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope="" itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="大括号">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">深入理解Java-8-Lambda表达式（Oracle官方文档版）</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2017-11-15T15:32:50+08:00">
                2017-11-15
              </time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope="" itemtype="http://schema.org/Thing">
                  <a href="/categories/我是一枚程序员/" itemprop="url" rel="index">
                    <span itemprop="name">我是一枚程序员</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          
            <span class="post-meta-divider">|</span>
            <span class="page-pv"><i class="fa fa-file-o"></i> 浏览
            <span class="busuanzi-value" id="busuanzi_value_page_pv"></span>次
            </span>
          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <blockquote>
<p>Java 8 问世三年了，9马上也要问世了，所以，嗯，我要开始学8了……</p>
</blockquote>
<p>官方文档：<a href="http://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html" rel="external nofollow noopener noreferrer" target="_blank">http://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html</a></p>
<h2 id="为什么用Lambda表达式"><a href="#为什么用Lambda表达式" class="headerlink" title="为什么用Lambda表达式"></a>为什么用Lambda表达式</h2><h5 id="只是代码简洁了这个好处的话，并不能打动很多观众，java-8也不会这么令人期待，其实java-8引入lambda迫切需求是因为lambda-表达式能简化集合上数据的多线程或者多核的处理，提供更快的集合处理速度"><a href="#只是代码简洁了这个好处的话，并不能打动很多观众，java-8也不会这么令人期待，其实java-8引入lambda迫切需求是因为lambda-表达式能简化集合上数据的多线程或者多核的处理，提供更快的集合处理速度" class="headerlink" title="只是代码简洁了这个好处的话，并不能打动很多观众，java 8也不会这么令人期待，其实java 8引入lambda迫切需求是因为lambda 表达式能简化集合上数据的多线程或者多核的处理，提供更快的集合处理速度 "></a><strong>只是代码简洁了这个好处的话，并不能打动很多观众，java 8也不会这么令人期待，其实java 8引入lambda迫切需求是因为lambda 表达式能简化集合上数据的多线程或者多核的处理，提供更快的集合处理速度 </strong></h5><p>匿名类的问题是，如果您的匿名类的实现非常简单，例如仅包含一个方法的接口，则匿名类的语法可能看起来很笨重且不清楚。在这些情况下，您通常会尝试将功能作为参数传递给另一种方法，例如当有人点击按钮时应该采取什么措施。Lambda表达式使您能够执行此操作，将功能视为方法参数或代码作为数据。</p>
<h2 id="文章概览"><a href="#文章概览" class="headerlink" title="文章概览"></a>文章概览</h2><ul>
<li>Lambda表达式的理想用例</li>
<li>方法1：创建搜索匹配一个特征的成员的方法</li>
<li>方法2：创建更广泛的搜索方法</li>
<li>方法3：在本地类中指定搜索条件代码</li>
<li>方法4：在匿名类中指定搜索条件代码</li>
<li>方法5：使用Lambda表达式指定搜索条件代码</li>
<li>方法6：使用带有Lambda表达式的标准功能接口</li>
<li>方法7：在整个应用程序中使用Lambda表达式</li>
<li>方法8：更广泛地使用泛型</li>
<li>方法9：使用接受Lambda表达式作为参数的聚合操作</li>
<li>GUI应用程序中的Lambda表达式</li>
<li>Lambda表达式的语法</li>
<li>访问封闭范围的局部变量</li>
<li>目标打字</li>
<li>目标类型和方法参数</li>
<li>序列化</li>
</ul>
<h3 id="Lambda表达式的理想用例"><a href="#Lambda表达式的理想用例" class="headerlink" title="Lambda表达式的理想用例"></a>Lambda表达式的理想用例</h3><p>假设您正在创建一个社交网络应用程序。您想要创建一个功能，使管理员可以在符合特定条件的社交网络应用程序的成员上执行任何类型的操作（例如发送消息）。下表详细描述了这种用例：<br><img src="http://upload-images.jianshu.io/upload_images/2833665-be157a8464886ba7.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt=""><br>假设这个社交网络应用程序的成员由以下Person类别表示 ：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line">public class Person &#123;</span><br><span class="line"></span><br><span class="line">    public enum Sex &#123;</span><br><span class="line">        MALE, FEMALE</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    String name;</span><br><span class="line">    LocalDate birthday;</span><br><span class="line">    Sex gender;</span><br><span class="line">    String emailAddress;</span><br><span class="line"></span><br><span class="line">    public int getAge() &#123;</span><br><span class="line">        // ...</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    public void printPerson() &#123;</span><br><span class="line">        // ...</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>假设您的社交网络应用程序的成员存储在一个List<person>实例中。<br>本节首先介绍了这种用例的天真的方法。<br>它使用本地和匿名类改进了这种方法，然后使用lambda表达式使用高效简明的方法来完成。<br><strong>方法1：创建搜索匹配一个特征的成员的方法</strong></person></p>
<p>一种简单的方法是创建几种方法; 每个方法搜索符合一个特征的成员，如性别或年龄。以下方法打印比指定年龄更早的成员：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">public static void printPersonsOlderThan(List&lt;Person&gt; roster, int age) &#123;</span><br><span class="line">    for (Person p : roster) &#123;</span><br><span class="line">        if (p.getAge() &gt;= age) &#123;</span><br><span class="line">            p.printPerson();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p><strong>注意</strong>：A 集合是一个对象，该组中的多个元素到单个单元中。集合用于存储，检索，操纵和传达聚合数据。</p>
<blockquote>
<p>这种方法可能会使您的应用程序变得脆弱，这是因为引入更新（例如较新的数据类型）而导致应用程序无法正常工作的可能性。假设您升级应用程序并更改Person类的结构，使其包含不同的成员变量; 可能是使用不同数据类型或算法的类记录和测量年龄。您将不得不重写很多API以适应这种变化。此外，这种方法是不必要的限制; 例如，如果你想打印比一定年龄小的成员怎么办？</p>
</blockquote>
<p><strong>方法2：创建更广泛的搜索方法</strong><br>以下方法比通用更为普遍printPersonsOlderThan; 会在特定范围内打印成员：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">public static void printPersonsWithinAgeRange(</span><br><span class="line">    List&lt;Person&gt; roster, int low, int high) &#123;</span><br><span class="line">    for (Person p : roster) &#123;</span><br><span class="line">        if (low &lt;= p.getAge() &amp;&amp; p.getAge() &lt; high) &#123;</span><br><span class="line">            p.printPerson();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>如果要打印指定性别的成员或指定的性别和年龄范围的组合，该怎么办？如果您决定更改Person课程并添加其他属性（如关系状态或地理位置），该怎么办？虽然这种方法比一般的方法更多printPersonsOlderThan，但是为每个可能的搜索查询创建一个单独的方法仍然可能导致脆弱的代码。您可以将指定要在其他类中搜索的条件的代码分开。<br><strong>方法3：在本地类中指定搜索条件代码</strong><br>以下方法打印与您指定的搜索条件匹配的成员：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">public static void printPersons(</span><br><span class="line">    List&lt;Person&gt; roster, CheckPerson tester) &#123;</span><br><span class="line">    for (Person p : roster) &#123;</span><br><span class="line">        if (tester.test(p)) &#123;</span><br><span class="line">            p.printPerson();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>该方法通过调用该方法来检查参数中Person包含的每个实例是否满足参数中指定的搜索条件。如果方法返回一个值，那么该方法在实例上被调用。ListrosterCheckPersontestertester.testtester.testtrueprintPersonsPerson要指定搜索条件，您可以实现该 CheckPerson接口：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">interface CheckPerson &#123;</span><br><span class="line">    boolean test(Person p);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>以下类CheckPerson通过指定方法的实现来实现接口test。该方法可以筛选符合美国Selective Service的成员：true如果Person参数为男性且年龄在18至25之间，则返回值：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">class CheckPersonEligibleForSelectiveService implements CheckPerson &#123;</span><br><span class="line">    public boolean test(Person p) &#123;</span><br><span class="line">        return p.gender == Person.Sex.MALE &amp;&amp;</span><br><span class="line">            p.getAge() &gt;= 18 &amp;&amp;</span><br><span class="line">            p.getAge() &lt;= 25;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>要使用此类，您将创建一个新的实例并调用printPersons方法：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">printPersons(  roster, new CheckPersonEligibleForSelectiveService());</span><br></pre></td></tr></table></figure></p>
<p>虽然这种方法不那么脆弱 - 如果您更改了结构，您不必重写方法Person- 您仍然有其他代码：您计划在应用程序中执行的每个搜索的新界面和本地类。因为CheckPersonEligibleForSelectiveService 实现一个接口，你可以使用一个匿名类而不是一个本地类，并绕过需要为每个搜索声明一个新的类。<br><strong>方法4：在匿名类中指定搜索条件代码</strong><br>以下调用该方法printPersons的一个参数是一个匿名类，用于过滤在美国有资格选择性服务的成员：男性，年龄在18至25岁之间的成员：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">printPersons(</span><br><span class="line">    roster,</span><br><span class="line">    new CheckPerson() &#123;</span><br><span class="line">        public boolean test(Person p) &#123;</span><br><span class="line">            return p.getGender() == Person.Sex.MALE</span><br><span class="line">                &amp;&amp; p.getAge() &gt;= 18</span><br><span class="line">                &amp;&amp; p.getAge() &lt;= 25;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">);</span><br></pre></td></tr></table></figure></p>
<p>这种方法减少了所需的代码量，因为您不必为每个要执行的搜索创建一个新类。然而，匿名类的语法是庞大的，因为CheckPerson接口只包含一种方法。在这种情况下，您可以使用lambda表达式而不是匿名类，如下一节所述。<br><strong>方法5：使用Lambda表达式指定搜索条件代码</strong><br>该CheckPerson接口是一个<em>功能接口</em>。功能界面是只包含一个抽象方法的任何接口 。功能界面可能包含一个或多个 默认方法静态方法由于功能界面只包含一个抽象方法，因此在实现时可以省略该方法的名称。为此，您不必使用匿名类表达式，而是使用<em>lambda表达式</em>，该<em>表达式</em>在以下方法调用中突出显示：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">printPersons(</span><br><span class="line">    roster,</span><br><span class="line">    (Person p) -&gt; p.getGender() == Person.Sex.MALE</span><br><span class="line">        &amp;&amp; p.getAge() &gt;= 18</span><br><span class="line">        &amp;&amp; p.getAge() &lt;= 25</span><br><span class="line">);</span><br><span class="line">`</span><br></pre></td></tr></table></figure></p>
<p>有关如何定义lambda表达式的信息，<br>请参阅<a href="http://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html#syntax" rel="external nofollow noopener noreferrer" target="_blank">Lambda表达式的语法</a>。您可以使用标准功能界面来代替接口CheckPerson，这进一步减少了所需的代码量。</p>
<p><strong>方法6：使用带有Lambda表达式的标准功能接口</strong><br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">Reconsider the CheckPerson interface:</span><br><span class="line"></span><br><span class="line">interface CheckPerson &#123;</span><br><span class="line">    boolean test(Person p);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>这是一个非常简单的界面。它是一个功能界面，因为它只包含一个抽象方法。该方法需要一个参数并返回一个 boolean值。该方法非常简单，可能不值得在应用程序中定义一个。因此，JDK定义了几个标准的功能接口，您可以在包中找到它们java.util.function。<br>例如，您可以使用该 Predicate<t> 界面代替CheckPerson。该界面包含以下方法boolean test(T t)：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line">interface Predicate&lt;T&gt; &#123;</span><br><span class="line">    boolean test(T t);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></t></p>
<p>该接口Predicate<t>是通用接口的示例。通用类型（如通用接口）在尖括号（&lt;&gt;）中指定一个或多个类型参数。此接口只包含一个类型参数T。当您使用实际类型参数声明或实例化通用类型时，您将具有参数化类型。例如，参数化类型Predicate<person>如下：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">interface Predicate&lt;Person&gt; &#123;</span><br><span class="line">    boolean test(Person t);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></person></t></p>
<p>此参数化类型包含一个具有相同返回类型和参数的方法CheckPerson.boolean test(Person p)。因此，您可以使用以下方法Predicate<t>来代替CheckPerson：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">public static void printPersonsWithPredicate(</span><br><span class="line">    List&lt;Person&gt; roster, Predicate&lt;Person&gt; tester) &#123;</span><br><span class="line">    for (Person p : roster) &#123;</span><br><span class="line">        if (tester.test(p)) &#123;</span><br><span class="line">            p.printPerson();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></t></p>
<p>因此，以下方法调用与printPersons在方法3中调用时相同 ：在本地类中指定搜索条件代码以获取符合选择性服务的成员：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">printPersonsWithPredicate(</span><br><span class="line">    roster,</span><br><span class="line">    p -&gt; p.getGender() == Person.Sex.MALE</span><br><span class="line">        &amp;&amp; p.getAge() &gt;= 18</span><br><span class="line">        &amp;&amp; p.getAge() &lt;= 25</span><br><span class="line">);</span><br></pre></td></tr></table></figure></p>
<p>这不是使用lambda表达式的唯一可能的方法。以下方法建议使用lambda表达式的其他方法。<br><strong>方法7：在整个应用程序中使用Lambda表达式</strong><br>重新考虑printPersonsWithPredicate 使用lambda表达式的方法：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">public static void printPersonsWithPredicate(</span><br><span class="line">    List&lt;Person&gt; roster, Predicate&lt;Person&gt; tester) &#123;</span><br><span class="line">    for (Person p : roster) &#123;</span><br><span class="line">        if (tester.test(p)) &#123;</span><br><span class="line">            p.printPerson();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>该方法检查参数中Person包含的每个实例是否满足参数中指定的条件。如果实例满足由此指定的条件，则该实例将调用该方法。ListrosterPredicatetesterPersontesterprintPersronPerson</p>
<p>而不是调用该方法printPerson，您可以指定在Person满足指定条件的那些实例上执行的其他操作tester。您可以使用lambda表达式指定此操作。假设你想要一个类似于一个lambda表达式printPerson，一个参数（一个类型的对象Person）并返回void。记住，要使用lambda表达式，您需要实现一个功能界面。在这种情况下，您需要一个包含抽象方法的功能界面，该方法可以使用一个类型的参数Person并返回void。该 Consumer<t> 界面包含void accept(T t)具有这些特征的方法 。以下方法将p.printPerson()使用Consumer<person>调用该方法的实例替换该调用 accept：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">public static void processPersons(</span><br><span class="line">    List&lt;Person&gt; roster,</span><br><span class="line">    Predicate&lt;Person&gt; tester,</span><br><span class="line">    Consumer&lt;Person&gt; block) &#123;</span><br><span class="line">        for (Person p : roster) &#123;</span><br><span class="line">            if (tester.test(p)) &#123;</span><br><span class="line">                block.accept(p);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></person></t></p>
<p>因此，以下方法调用与printPersons在方法3中调用的方法相同：在本地类中指定搜索条件代码以获取符合选择性服务的成员。用于打印成员的lambda表达式突出显示：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">processPersons(</span><br><span class="line">     roster,</span><br><span class="line">     p -&gt; p.getGender() == Person.Sex.MALE</span><br><span class="line">         &amp;&amp; p.getAge() &gt;= 18</span><br><span class="line">         &amp;&amp; p.getAge() &lt;= 25,</span><br><span class="line">     p -&gt; p.printPerson()</span><br><span class="line">);</span><br></pre></td></tr></table></figure></p>
<p>如果您想要更多地使用会员的个人资料，而不是打印出来。假设您要验证会员的个人资料或检索他们的联系信息？在这种情况下，您需要一个功能界面，其中包含一个返回值的抽象方法。该 Function<t,r> 接口包含的方法R apply(T t)。以下方法检索由参数指定的数据mapper，然后对该参数指定的操作执行操作block：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">public static void processPersonsWithFunction(</span><br><span class="line">    List&lt;Person&gt; roster,</span><br><span class="line">    Predicate&lt;Person&gt; tester,</span><br><span class="line">    Function&lt;Person, String&gt; mapper,</span><br><span class="line">    Consumer&lt;String&gt; block) &#123;</span><br><span class="line">    for (Person p : roster) &#123;</span><br><span class="line">        if (tester.test(p)) &#123;</span><br><span class="line">            String data = mapper.apply(p);</span><br><span class="line">            block.accept(data);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></t,r></p>
<p>以下方法从包含在roster哪些符合选择性服务的每个成员中检索电子邮件地址，然后打印：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">processPersonsWithFunction(</span><br><span class="line">    roster,</span><br><span class="line">    p -&gt; p.getGender() == Person.Sex.MALE</span><br><span class="line">        &amp;&amp; p.getAge() &gt;= 18</span><br><span class="line">        &amp;&amp; p.getAge() &lt;= 25,</span><br><span class="line">    p -&gt; p.getEmailAddress(),</span><br><span class="line">    email -&gt; System.out.println(email)</span><br><span class="line">);</span><br></pre></td></tr></table></figure></p>
<p><strong>方法8：更广泛地使用泛型</strong></p>
<p>重新考虑该方法processPersonsWithFunction。以下是它的一般版本，它接受包含任何数据类型元素的集合作为参数：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">public static &lt;X, Y&gt; void processElements(</span><br><span class="line">    Iterable&lt;X&gt; source,</span><br><span class="line">    Predicate&lt;X&gt; tester,</span><br><span class="line">    Function &lt;X, Y&gt; mapper,</span><br><span class="line">    Consumer&lt;Y&gt; block) &#123;</span><br><span class="line">    for (X p : source) &#123;</span><br><span class="line">        if (tester.test(p)) &#123;</span><br><span class="line">            Y data = mapper.apply(p);</span><br><span class="line">            block.accept(data);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>要打印符合选择性服务的会员的电子邮件地址，请调用以下processElements方法：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">processElements(</span><br><span class="line">    roster,</span><br><span class="line">    p -&gt; p.getGender() == Person.Sex.MALE</span><br><span class="line">        &amp;&amp; p.getAge() &gt;= 18</span><br><span class="line">        &amp;&amp; p.getAge() &lt;= 25,</span><br><span class="line">    p -&gt; p.getEmailAddress(),</span><br><span class="line">    email -&gt; System.out.println(email)</span><br><span class="line">);</span><br></pre></td></tr></table></figure></p>
<p>此方法调用执行以下操作：</p>
<ul>
<li><p>1.从集合中获取对象的源source。在此示例中，它Person从集合中获取对象的源roster。请注意，作为roster类型集合的集合也是类型List的对象Iterable。</p>
</li>
<li><ol>
<li>过滤与该Predicate对象匹配的对象tester。在此示例中，该Predicate对象是一个lambda表达式，用于指定哪些成员将具有选择性服务的资格。</li>
</ol>
</li>
<li><p>3.映射由指定的每个经滤波的对象的值Function的对象mapper。在此示例中，该Function对象是一个返回成员的电子邮件地址的lambda表达式。</p>
</li>
<li><p>4.由指定执行每个映射对象的动作Consumer对象block。在这个例子中，该Consumer对象是一个lambda表达式，它打印一个字符串，它是Function对象返回的电子邮件地址。<br>您可以使用聚合操作替换这些操作。</p>
</li>
</ul>
<p><strong>方法9：使用接受Lambda表达式作为参数的聚合操作</strong><br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">roster</span><br><span class="line">    .stream()</span><br><span class="line">    .filter(</span><br><span class="line">        p -&gt; p.getGender() == Person.Sex.MALE</span><br><span class="line">            &amp;&amp; p.getAge() &gt;= 18</span><br><span class="line">            &amp;&amp; p.getAge() &lt;= 25)</span><br><span class="line">    .map(p -&gt; p.getEmailAddress())</span><br><span class="line">    .forEach(email -&gt; System.out.println(email));</span><br><span class="line">`</span><br></pre></td></tr></table></figure></p>
<p>下表列出了方法processElements执行的每个操作与相应的聚合操作：</p>
<p><img src="http://upload-images.jianshu.io/upload_images/2833665-5a47139c88b47626.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt=""><br>操作filter，map并且forEach是聚合操作。从流中聚合操作流程元素，而不是直接从集合（这是在这个示例中调用的第一个方法的原因stream）。甲流是元素的序列。与集合不同，它不是存储元素的数据结构。相反，流携带来自源的值，例如通过管道的收集。甲管道是流的操作的序列，其在该示例中是filter- - 。map forEach另外，聚合操作通常接受lambda表达式作为参数，使您可以自定义它们的行为。</p>
<p><strong> GUI应用程序中的Lambda表达式</strong><br>要在图形用户界面（GUI）应用程序（如键盘操作，鼠标操作和滚动操作）中处理事件，您通常会创建事件处理程序，通常涉及实现特定接口。事件处理接口通常是功能接口; 他们往往只有一种方法。<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">btn.setOnAction（new EventHandler &lt;ActionEvent&gt;（）&#123;</span><br><span class="line"></span><br><span class="line">           @Override </span><br><span class="line">           public void handle（ActionEvent event）&#123; </span><br><span class="line">               System.out.println（“Hello World！”）; </span><br><span class="line">           &#125; </span><br><span class="line">       &#125;）;</span><br></pre></td></tr></table></figure></p>
<p>方法调用btn.setOnAction指定当您选择由btn对象表示的按钮时会发生什么。此方法需要一个类型的对象EventHandler<actionevent>。该EventHandler<actionevent> 界面只包含一种方法void handle(T event)。此接口是一个功能界面，因此您可以使用以下突出显示的lambda表达式来替换它：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">btn.setOnAction（</span><br><span class="line">          event  - &gt; System.out.println（“Hello World！”） </span><br><span class="line">       ）;</span><br></pre></td></tr></table></figure></actionevent></actionevent></p>
<h3 id="Lambda表达式的语法"><a href="#Lambda表达式的语法" class="headerlink" title="Lambda表达式的语法"></a>Lambda表达式的语法</h3><ul>
<li>用括号括起来的逗号分隔的形式参数列表。该CheckPerson.test方法包含一个参数， p它表示Person该类的一个实例 。</li>
</ul>
<blockquote>
<p>注意：您可以忽略lambda表达式中参数的数据类型。另外，如果只有一个参数，可以省略括号。例如，以下lambda表达式也是有效的：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">p  - &gt; p.getGender（）== Person.Sex.MALE </span><br><span class="line">    &amp;&amp; p.getAge（）&gt; = 18</span><br><span class="line">    &amp;&amp; p.getAge（）&lt;= 25</span><br></pre></td></tr></table></figure></p>
</blockquote>
<ul>
<li><p>箭头令牌， -&gt;</p>
</li>
<li><p>一个由单个表达式或语句块组成的主体。此示例使用以下表达式：</p>
</li>
</ul>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">p.getGender（）== Person.Sex.MALE </span><br><span class="line">    &amp;&amp; p.getAge（）&gt; = 18</span><br><span class="line">    &amp;&amp; p.getAge（）&lt;= 25</span><br></pre></td></tr></table></figure>
<p>如果指定单个表达式，则Java运行时将评估表达式，然后返回其值。或者，您可以使用return语句：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">p -&gt; &#123;</span><br><span class="line">    return p.getGender() == Person.Sex.MALE</span><br><span class="line">        &amp;&amp; p.getAge() &gt;= 18</span><br><span class="line">        &amp;&amp; p.getAge() &lt;= 25;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>return语句不是表达式; 在lambda表达式中，您必须用大括号（{}）括起来。但是，您不必在大括号中包含一个void方法调用。例如，以下是有效的lambda表达式：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">email -&gt; System.out.println(email)</span><br></pre></td></tr></table></figure></p>
<p>请注意，lambda表达式看起来很像一个方法声明; 您可以将lambda表达式视为匿名方法 - 没有名称的方法。</p>
<p>以下示例 Calculator是使用多个形式参数的lambda表达式的示例：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line">public class Calculator &#123;</span><br><span class="line">  </span><br><span class="line">    interface IntegerMath &#123;</span><br><span class="line">        int operation(int a, int b);   </span><br><span class="line">    &#125;</span><br><span class="line">  </span><br><span class="line">    public int operateBinary(int a, int b, IntegerMath op) &#123;</span><br><span class="line">        return op.operation(a, b);</span><br><span class="line">    &#125;</span><br><span class="line"> </span><br><span class="line">    public static void main(String... args) &#123;</span><br><span class="line">    </span><br><span class="line">        Calculator myApp = new Calculator();</span><br><span class="line">        IntegerMath addition = (a, b) -&gt; a + b;</span><br><span class="line">        IntegerMath subtraction = (a, b) -&gt; a - b;</span><br><span class="line">        System.out.println(&quot;40 + 2 = &quot; +</span><br><span class="line">            myApp.operateBinary(40, 2, addition));</span><br><span class="line">        System.out.println(&quot;20 - 10 = &quot; +</span><br><span class="line">            myApp.operateBinary(20, 10, subtraction));    </span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>该方法operateBinary对两个整数操作数进行数学运算。操作本身由一个实例指定IntegerMath。的例子中定义了lambda表达式两个操作，addition和subtraction。该示例打印以下内容：</p>
<blockquote>
<p>40 + 2 = 42<br>20  -  10 = 10</p>
</blockquote>
<p><strong>访问封闭范围的局部变量</strong></p>
<p>像本地和匿名类一样，lambda表达式可以 捕获变量 ; 它们对包围范围的局部变量具有相同的访问权限。但是，与本地和匿名类不同，lambda表达式没有任何阴影问题（有关详细信息，请参阅 阴影）。Lambda表达式是词法的范围。这意味着它们不会从超类型继承任何名称或引入新的范围界定。lambda表达式中的声明就像在封闭环境中一样被解释。以下示例 LambdaScopeTest演示如下：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line">import java.util.function.Consumer;</span><br><span class="line"></span><br><span class="line">public class LambdaScopeTest &#123;</span><br><span class="line"></span><br><span class="line">    public int x = 0;</span><br><span class="line"></span><br><span class="line">    class FirstLevel &#123;</span><br><span class="line"></span><br><span class="line">        public int x = 1;</span><br><span class="line"></span><br><span class="line">        void methodInFirstLevel(int x) &#123;</span><br><span class="line">            </span><br><span class="line">            // The following statement causes the compiler to generate</span><br><span class="line">            // the error &quot;local variables referenced from a lambda expression</span><br><span class="line">            // must be final or effectively final&quot; in statement A:</span><br><span class="line">            //</span><br><span class="line">            // x = 99;</span><br><span class="line">            </span><br><span class="line">            Consumer&lt;Integer&gt; myConsumer = (y) -&gt; </span><br><span class="line">            &#123;</span><br><span class="line">                System.out.println(&quot;x = &quot; + x); // Statement A</span><br><span class="line">                System.out.println(&quot;y = &quot; + y);</span><br><span class="line">                System.out.println(&quot;this.x = &quot; + this.x);</span><br><span class="line">                System.out.println(&quot;LambdaScopeTest.this.x = &quot; +</span><br><span class="line">                    LambdaScopeTest.this.x);</span><br><span class="line">            &#125;;</span><br><span class="line"></span><br><span class="line">            myConsumer.accept(x);</span><br><span class="line"></span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    public static void main(String... args) &#123;</span><br><span class="line">        LambdaScopeTest st = new LambdaScopeTest();</span><br><span class="line">        LambdaScopeTest.FirstLevel fl = st.new FirstLevel();</span><br><span class="line">        fl.methodInFirstLevel(23);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>T此示例生成以下输出：</p>
<blockquote>
<p>x = 23<br>y = 23<br>this.x = 1<br>LambdaScopeTest.this.x = 0</p>
</blockquote>
<p>如果在lambda表达式的声明中替换参数x，编译器将生成一个错误：ymyConsumer<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">Consumer&lt;Integer&gt; myConsumer = (x) -&gt; &#123;</span><br><span class="line">    // ...</span><br><span class="line">&#125;</span><br><span class="line">`</span><br></pre></td></tr></table></figure></p>
<p>编译器生成错误“变量x已经在方法methodInFirstLevel（int）中定义”，因为lambda表达式不会引入新的一级范围。因此，您可以直接访问封闭范围的字段，方法和局部变量。例如，lambda表达式直接访问x该方法的参数methodInFirstLevel。要访问包围类中的变量，请使用关键字this。在这个例子中，this.x指的是成员变量FirstLevel.x。</p>
<p>然而，像本地和匿名类一样，lambda表达式只能访问最终或有效最终的封闭块的局部变量和参数。例如，假设您在methodInFirstLevel定义语句之后立即添加以下赋值语句：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">void methodInFirstLevel(int x) &#123;</span><br><span class="line">    x = 99;</span><br><span class="line">    // ...</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>由于这个赋值语句，变量FirstLevel.x不再是有效的最终了。因此，Java编译器会生成类似于“lambda表达式引用的本地变量必须是final”或“final”的错误消息，其中lambda表达式myConsumer尝试访问该FirstLevel.x变量：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">System.out.println（“x =”+ x）;</span><br></pre></td></tr></table></figure>
<h3 id="目标打字"><a href="#目标打字" class="headerlink" title="目标打字"></a>目标打字</h3><p>你如何确定一个lambda表达式的类型？<br>回想一下选择的男性和18至25岁之间的成员的lambda表达：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">p - &gt; p.getGender（）== Person.Sex.MALE</span><br><span class="line">&amp;&amp; p.getAge（）&gt; = 18</span><br><span class="line">&amp;&amp; p.getAge（）&lt;= 25</span><br></pre></td></tr></table></figure></p>
<p>public static void printPersons(List<person> roster, CheckPerson tester)<br>在<a href="http://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html#approach3" rel="external nofollow noopener noreferrer" target="_blank">方法3：在局部类指定搜索条件码</a></person></p>
<p>public void printPersonsWithPredicate(List<person> roster, Predicate<person> tester)<br>在<a href="http://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html#approach6" rel="external nofollow noopener noreferrer" target="_blank">方法6：Lambda表达式使用标准的功能接口</a>当Java运行时调用该方法时</person></person></p>
<p>printPersons，它期望数据类型CheckPerson，因此lambda表达式是这种类型的。但是，当Java运行时调用该方法时<br>printPersonsWithPredicate，它期待数据类型Predicate<person>，因此lambda表达式是这种类型的。这些方法期望的数据类型称为<em>目标类型</em>。<br>要确定lambda表达式的类型，Java编译器将使用上下文的目标类型或其中找到lambda表达式的情境。<br>因此，您只能在Java编译器可以确定目标类型的情况下使用lambda表达式：</person></p>
<blockquote>
<p>变量声明<br>分配<br>回报表<br>阵列初始化器<br>方法或构造函数参数<br>Lambda表达体<br>条件表达式， ?:<br>演员表达式<br>目标类型和方法参数</p>
</blockquote>
<p>对于方法参数，Java编译器使用其他两种语言功能来确定目标类型：重载解析和类型参数推断。</p>
<p>考虑以下两个功能界面（ <a href="https://docs.oracle.com/javase/8/docs/api/java/lang/Runnable.html" rel="external nofollow noopener noreferrer" target="_blank">java.lang.Runnable</a>和 <a href="https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Callable.html" rel="external nofollow noopener noreferrer" target="_blank">java.util.concurrent.Callable<v></v></a>）：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">public interface Runnable &#123;</span><br><span class="line">    void run();</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">public interface Callable&lt;V&gt; &#123;</span><br><span class="line">    V call();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>该方法Runnable.run不返回值，而是Callable<v>.call。假设您已经invoke按照以下方法重载了该方法<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">void invoke(Runnable r) &#123;</span><br><span class="line">    r.run();</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">&lt;T&gt; T invoke(Callable&lt;T&gt; c) &#123;</span><br><span class="line">    return c.call();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></v></p>
<p>在以下语句中将调用哪种方法？</p>
<p>String s = invoke（（） - &gt;“done”）;</p>
<p>该方法invoke(Callable<t>)将被调用，因为该方法返回一个值; 该方法 invoke(Runnable)没有。在这种情况下，lambda表达式的类型() -&gt; “done”是Callable<t>。</t></t></p>
<h3 id="序列化"><a href="#序列化" class="headerlink" title="序列化"></a>序列化</h3><p>如果lambda表达式的目标类型及其捕获的参数是可序列化的，则可以 序列化它。然而，像 内部类一样，强烈地不鼓励lambda表达式的序列化。</p>

      
    </div>
    
    
    

    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>文章不错，你都不请我喝杯茶，就是说你呀！</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/images/wechatpay.png" alt="无可替代 微信支付">
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="/images/alipay.png" alt="无可替代 支付宝">
        <p>支付宝</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    

    <footer class="post-footer">
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/posts/3598/" rel="next" title="网站升级为https过程记录-tomcat">
                <i class="fa fa-chevron-left"></i> 网站升级为https过程记录-tomcat
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/posts/60251/" rel="prev" title="如何使用Intellij调试AngularJS">
                如何使用Intellij调试AngularJS <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope="" itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image" src="/images/touxiang.jpg" alt="无可替代">
            
              <p class="site-author-name" itemprop="name">无可替代</p>
              <p class="site-description motion-element" itemprop="description">大括号的博客</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">129</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">11</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            

          </nav>

          

          <div class="links-of-author motion-element">
            
              
                <span class="links-of-author-item">
                  <a href="https://github.com/liepeng328" target="_blank" title="GitHub" rel="external nofollow noopener noreferrer">
                    
                      <i class="fa fa-fw fa-github"></i>GitHub</a>
                </span>
              
                <span class="links-of-author-item">
                  <a href="https://gitee.com/lovepeng" target="_blank" title="码云" rel="external nofollow noopener noreferrer">
                    
                      <i class="fa fa-fw fa-globe"></i>码云</a>
                </span>
              
                <span class="links-of-author-item">
                  <a href="https://coding.net/u/dakuohao" target="_blank" title="Coding" rel="external nofollow noopener noreferrer">
                    
                      <i class="fa fa-fw fa-globe"></i>Coding</a>
                </span>
              
                <span class="links-of-author-item">
                  <a href="https://www.toutiao.com/c/user/2585432515/#mid=6741594486" target="_blank" title="今日头条" rel="external nofollow noopener noreferrer">
                    
                      <i class="fa fa-fw fa-globe"></i>今日头条</a>
                </span>
              
                <span class="links-of-author-item">
                  <a href="https://www.zhihu.com/people/dakuohao/activities" target="_blank" title="知乎" rel="external nofollow noopener noreferrer">
                    
                      <i class="fa fa-fw fa-globe"></i>知乎</a>
                </span>
              
                <span class="links-of-author-item">
                  <a href="http://www.jianshu.com/u/4ea0af17fd67" target="_blank" title="简书" rel="external nofollow noopener noreferrer">
                    
                      <i class="fa fa-fw fa-globe"></i>简书</a>
                </span>
              
                <span class="links-of-author-item">
                  <a href="http://mail.qq.com/cgi-bin/qm_share?t=qm_mailme&email=hOjr8uH04erjt7a8xPX1qufr6Q" target="_blank" title="E-Mail" rel="external nofollow noopener noreferrer">
                    
                      <i class="fa fa-fw fa-globe"></i>E-Mail</a>
                </span>
              
                <span class="links-of-author-item">
                  <a href="https://jq.qq.com/?_wv=1027&k=5ISEgpc" target="_blank" title="QQ群" rel="external nofollow noopener noreferrer">
                    
                      <i class="fa fa-fw fa-globe"></i>QQ群</a>
                </span>
              
            
          </div>

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#为什么用Lambda表达式"><span class="nav-number">1.</span> <span class="nav-text">为什么用Lambda表达式</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#只是代码简洁了这个好处的话，并不能打动很多观众，java-8也不会这么令人期待，其实java-8引入lambda迫切需求是因为lambda-表达式能简化集合上数据的多线程或者多核的处理，提供更快的集合处理速度"><span class="nav-number">1.0.0.1.</span> <span class="nav-text">只是代码简洁了这个好处的话，并不能打动很多观众，java 8也不会这么令人期待，其实java 8引入lambda迫切需求是因为lambda 表达式能简化集合上数据的多线程或者多核的处理，提供更快的集合处理速度 </span></a></li></ol></li></ol><li class="nav-item nav-level-2"><a class="nav-link" href="#文章概览"><span class="nav-number">2.</span> <span class="nav-text">文章概览</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#Lambda表达式的理想用例"><span class="nav-number">2.1.</span> <span class="nav-text">Lambda表达式的理想用例</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Lambda表达式的语法"><span class="nav-number">2.2.</span> <span class="nav-text">Lambda表达式的语法</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#目标打字"><span class="nav-number">2.3.</span> <span class="nav-text">目标打字</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#序列化"><span class="nav-number">2.4.</span> <span class="nav-text">序列化</span></a></li></ol></li></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2017</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">无可替代</span>

  
</div>


  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io" rel="external nofollow noopener noreferrer">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next" rel="external nofollow noopener noreferrer">NexT.Pisces</a> v5.1.3</div>



<span class="post-meta-divider">|</span>
<div class="theme-info">
Hosted by <a class="theme-link" target="_blank" href="https://pages.coding.me" rel="external nofollow noopener noreferrer">Coding Pages</a>
</div>




        
<div class="busuanzi-count">
  <script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv">
      <i class="fa fa-user"></i> 访问人数
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
      
    </span>
  

  
    <span class="site-pv">
      <i class="fa fa-eye"></i> 访问总量
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
      次
    </span>
  
</div>








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  


  



  
  









  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  

  
  
    <script type="text/javascript" src="/lib/canvas-nest/canvas-nest.min.js"></script>
  

  
  
    <script type="text/javascript" src="/lib/three/three.min.js"></script>
  

  
  
    <script type="text/javascript" src="/lib/three/three-waves.min.js"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.3"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.3"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.3"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.3"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.3"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.3"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.3"></script>



  


  




	





  





  












  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  

  

  

  

</body>
</html>
